package cn.itlaobing.web.servlet;

import cn.itlaobing.web.annotation.RequsetMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.*;

/**
 * Created by admin on 2017/11/6.
 */

public class BaseServlet extends HttpServlet {
    private Map<String, Method> requestMapping = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //取得当前Servlet类的Class对象
        Class clsServlet = this.getClass();
        //取得WebServlet 对象获取基础的url
        WebServlet webServlet = (WebServlet) clsServlet.getAnnotation(WebServlet.class);
        String baseUrl = webServlet.value()[0];

        //反射取得所有的方法
        Method[] methods = clsServlet.getDeclaredMethods();
        //查看方法上是否标注了 @RequestMapping
        for (Method method : methods)
            if (method.isAnnotationPresent(RequsetMapping.class)) {
                RequsetMapping requsetMapping = method.getAnnotation(RequsetMapping.class);
                //获取url
                String url = requsetMapping.value();
                if (!url.startsWith("/")) {
                    url = "/" + url;
                }
                String fullUrl = baseUrl.replace("/*", "") + url;
                //保存到Map上
                requestMapping.put(fullUrl, method);
            }
        System.out.println(requestMapping);
    }


    private static final String PREFIX = "/WEB_INF/view";
    private static final String SUFFIX = ".jsp";

    protected void toView(HttpServletRequest request, HttpServletResponse response, String viewName) throws ServletException, IOException {
        try {
            request.getRequestDispatcher(PREFIX + viewName + SUFFIX).forward(request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void redirectTo(HttpServletResponse response, String url) throws ServletException, IOException {
        String contextPath = super.getServletContext().getContextPath();
        if (!url.startsWith("/")) {
            url += "/";
        }
        response.sendRedirect(contextPath + url);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //取得当前请求的url
        String requestURl = req.getRequestURI();
        System.out.println(requestURl);
        //从map中取得方法
        Method method = requestMapping.get(requestURl);
        if (method == null) {
            resp.sendError(404, "请求路径错误");
            return;
        }
        //调用方法法
        try {
            method.invoke(this, req, resp);

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}
